package com.baselib.libnetwork.net.utils;

import android.os.Environment;

import com.baselib.libnetwork.BuildConfig;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lixiaoyu
 * @version v1.0
 * @description
 * @since 2018/4/2
 */
public class LogWriteUtils {


    private static String NetTimePath = "NetTimePath";
    private static String floderName = "PieLog";
    private static String data = "yyyy-MM-dd";
    private static String dataTime = "yyyy-MM-dd hh:mm:ss";


    private static String creatFile(String anme) throws IOException {
        String sdCardPath = Environment.getExternalStorageDirectory().getPath();
        String floder = sdCardPath + File.separator + floderName;

        File floderFile = new File(floder);
        if (!floderFile.exists()) {
            floderFile.mkdir();
        }

        String logPath = floder + File.separator + anme;

        File mFile = new File(logPath);
        if (!mFile.exists()) {
            mFile.createNewFile();
        }
        return logPath;
    }

    public static void writeNetLog(String log) {
        if (!BuildConfig.DEBUG) {
            return;
        }
        RandomAccessFile raf = null;
        try {
            String fileName = creatFile(NetTimePath + getDataTime(data) + ".txt");

            File file = new File(fileName);
            byte[] buffer = (getDataTime(dataTime) + "---" + log).getBytes();
            raf = new RandomAccessFile(file, "rw");
            raf.seek(file.length());
            raf.write(buffer);
            raf.write("\n".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String getDataTime(String format) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(format);
        return sDateFormat.format(new Date(System.currentTimeMillis()));
    }
}
